package com.glasses.business.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import org.haitao.common.utils.*;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/4/24
 * Version：1.0
 */

public class Camerautils_ {
    public static final int TAKE_PICTURE = 1;
    public static final int TAKE_VIDEO = 2;
    public static final int LOCAL_PICTURE = 3;
    public static final int LOCAL_VIDEO = 4;
    public static final int REQUEST_CAMERA_PERMISSION = 5;
    public static String photoPath = null;

    public Camerautils_() {
    }

    public static String takePhoto(Activity ac, String path, String pictureName) {
        if(!hasCamera(ac)) {
            ToastUtil.shortShowCustom("没有相机");
            return "";
        } else if(org.haitao.common.utils.FileUtils.makeDir(path)) {
            Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
            cameraIntent.putExtra("orientation", 0);
            cameraIntent.addCategory("android.intent.category.DEFAULT");
            photoPath = path + "/" + pictureName;
            Uri imageUri = Uri.fromFile(new File(path, pictureName));
            cameraIntent.putExtra("output", imageUri);
            ac.startActivityForResult(cameraIntent, 1);
            AppLog.e("==========photoPath========="+photoPath);
            return path + "/" + pictureName;
        } else {
            ToastUtil.shortShowCustom("SD卡不可用");
            photoPath = null;
            return null;
        }
    }

    public static String takePhoto(Activity ac) {
        return takePhoto(ac, org.haitao.common.utils.FileUtils.getAppPath(), org.haitao.common.utils.FileUtils.getRandomName() + ".png");
    }

    public static boolean hasCamera(Activity ac) {
        PackageManager packageManager = ac.getPackageManager();
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        List list = packageManager.queryIntentActivities(intent, 65536);
        return list != null && list.size() > 0;
    }

    public static String getRandomName() {
        return TimeUtil.dateToString(new Date(), "yyyy_MM_dd_HH_mm_ss") + getRandom(0, 1000);
    }

    public static int getRandom(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }

    public static void takeVideo(Activity ac) {
        Intent intent = new Intent("android.media.action.VIDEO_CAPTURE");
        intent.putExtra("android.intent.extra.videoQuality", 1);
        ac.startActivityForResult(intent, 2);
    }

    public static void getLocalPicture(Activity ac) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction("android.intent.action.GET_CONTENT");
        ac.startActivityForResult(intent, 3);
    }

    public static void getLocalVideo(Activity ac) {
        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction("android.intent.action.GET_CONTENT");
        ac.startActivityForResult(intent, 4);
    }

    @SuppressLint({"NewApi"})
    public static String getPhotoByIntent(Context context, Intent data) {
        if(data == null) {
            return null;
        } else {
            String[] var10000 = new String[]{"_data"};
            Uri uri = data.getData();
            boolean isKitKat = Build.VERSION.SDK_INT >= 19;
            if(isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                String docId;
                String[] split;
                String type;
                if(isExternalStorageDocument(uri)) {
                    docId = DocumentsContract.getDocumentId(uri);
                    split = docId.split(":");
                    type = split[0];
                    if("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                } else {
                    if(isDownloadsDocument(uri)) {
                        docId = DocumentsContract.getDocumentId(uri);
                        Uri split1 = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId).longValue());
                        return getDataColumn(context, split1, (String)null, (String[])null);
                    }

                    if(isMediaDocument(uri)) {
                        docId = DocumentsContract.getDocumentId(uri);
                        split = docId.split(":");
                        type = split[0];
                        Uri contentUri = null;
                        if("image".equals(type)) {
                            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                        } else if("video".equals(type)) {
                            contentUri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                        } else if("audio".equals(type)) {
                            contentUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                        }

                        String selection = "_id=?";
                        String[] selectionArgs = new String[]{split[1]};
                        return getDataColumn(context, contentUri, "_id=?", selectionArgs);
                    }
                }
            } else {
                if("content".equalsIgnoreCase(uri.getScheme())) {
                    if(isGooglePhotosUri(uri)) {
                        return uri.getLastPathSegment();
                    }

                    return getDataColumn(context, uri, (String)null, (String[])null);
                }

                if("file".equalsIgnoreCase(uri.getScheme())) {
                    return uri.getPath();
                }
            }

            return null;
        }
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = "_data";
        String[] projection = new String[]{"_data"};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, (String)null);
            if(cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow("_data");
                String var9 = cursor.getString(index);
                return var9;
            }
        } finally {
            if(cursor != null) {
                cursor.close();
            }

        }

        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static String getVideoByIntent(Activity ac, Intent data) {
        String path = null;
        if(data == null) {
            path = null;
        } else {
            String[] proj = new String[]{"_data"};
            Uri originalUri = data.getData();
            Cursor cursor = ac.getContentResolver().query(originalUri, proj, (String)null, (String[])null, (String)null);
            if(cursor == null) {
                if(originalUri != null && originalUri.toString().length() > 11 && originalUri.toString().startsWith("file://")) {
                    String column_index = originalUri.toString().substring(originalUri.toString().length() - 3);
                    if(!column_index.equalsIgnoreCase("mp4") && !column_index.equalsIgnoreCase("avi") && !column_index.equalsIgnoreCase("flv") && !column_index.equalsIgnoreCase("mov")) {
                        ToastUtil.shortShowCustom("不是支持的视屏");
                    } else {
                        path = originalUri.toString().substring(7);
                    }
                } else {
                    ToastUtil.shortShowCustom("不是支持的视屏");
                }
            } else {
                int column_index1 = cursor.getColumnIndexOrThrow("_data");
                cursor.moveToFirst();
                path = cursor.getString(column_index1);
                if(path == null) {
                    ToastUtil.shortShowCustom("获取视频路径失败");
                }

                cursor.close();
            }
        }

        return path;
    }

    public static String getTakeVideoByIntent(Activity ac, Intent data) {
        String path = null;
        if(data != null) {
            Uri uri = data.getData();
            Cursor cursor = ac.getContentResolver().query(uri, (String[])null, (String)null, (String[])null, (String)null);
            if(cursor != null && cursor.moveToNext()) {
                path = cursor.getString(cursor.getColumnIndex("_data"));
                cursor.close();
            }
        }

        return path;
    }

    public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
        Bitmap bitmap = null;
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
        AppLog.e(bitmap);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, 2);
        AppLog.e(bitmap);
        return bitmap;
    }

    @SuppressLint({"NewApi"})
    public static Bitmap getVideoThumbnail(String filePath, int rightwidth, int rightheight) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();

        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime(-1L);
        } catch (IllegalArgumentException var20) {
            var20.printStackTrace();
        } catch (RuntimeException var21) {
            var21.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException var19) {
                var19.printStackTrace();
            }

        }

        if(bitmap == null) {
            return null;
        } else {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float scale = Math.min((float)width / (float)rightwidth, (float)height / (float)rightheight);
            int w = Math.round(scale * (float)rightwidth);
            int h = Math.round(scale * (float)rightheight);
            bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
            return bitmap;
        }
    }

    public static boolean isVideBigger(String path, int sizeM) {
        boolean flag = false;
        if(!org.haitao.common.utils.FileUtils.fileExit(path)) {
            ToastUtil.shortShowCustom("文件不存在");
        } else if(org.haitao.common.utils.FileUtils.getDirSize(new File(path)) > (double)sizeM) {
            ToastUtil.shortShowCustom("视频太大,请选择小于" + sizeM + "的视频");
        } else {
            flag = true;
        }

        return flag;
    }
}